// -*-mode:c++; coding:utf-8-*-

#include "column_name_parser.hpp"

#include "protocol_packet.hpp"
#include "row_mutation.hpp"
#include "row_mutation_data.hpp"

namespace xbase
{
	
	row_mutation::error_code row_mutation::add(const std::string &column_name,
						   const std::string &value,
						   uint64_t timestamp) const
	{
		error_code ec;
		const bool is_deletion = value.empty();
		const protocol::family_info * family = NULL;
		const column_name_parser parser(column_name);
		if(parser.has_regex())
		{
			ec = error::column_name_with_regexp;
		}
		else if(! parser.has_colon())
		{
			ec = error::bad_column_name;
		}
		else if((! is_deletion) && (column_name.empty()))
		{
			ec = error::empty_column_name;
		}
		else if((! is_deletion) && (! parser.has_qualifier_name()))
		{
			ec = error::empty_qualifier_name;
		}
		else if((! column_name.empty()) &&
			((family = m_table_info->get_family_info(parser.family_name())) == NULL))
		{
			ec = error::family_not_exists;
		}
		else if((family != NULL) && (! m_table_info->has_group(family->m_group_name)))
		{
			ec = error::group_not_exists;
		}
		else
		{
			if(family != NULL)
			{
				m_data->add(family->m_group_name,
					    column_name, value, timestamp);
			}
			else
			{
				typedef protocol::group_info_vector::iterator iter_t;
				const iter_t end = m_table_info->m_groups.end();
				for(iter_t it = m_table_info->m_groups.begin();
				    it != end; ++it)
				{
					m_data->add(it->m_group_name,
						    column_name, value, timestamp);
				}
			}
		}
		return ec;
	}

} // namespace xbase

